/**
 * FormGrupo.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormGrupo.java
 *
 * Created on 11/06/2009, 17:45:46
 */

package frames;

import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import negocio.produto.Grupo;
import utils.*;

/**
 *
 * @author jmsandy
 */
public class FormGrupo extends javax.swing.JDialog {

    //<editor-fold defaultstate="collapsed" desc="FIELDS">
    private Grupo grupo      = null;
    private ArrayList lstObj = null;
    private int posicao      = 0;
    private int situacao     = 0;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="CONSTANTS">
    public static final Integer K_FORM_PESQUISA = 1;
    public static final Integer K_FORM_CADASTRO = 2;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Acessores">
    public Grupo getGrupo(){
        return this.grupo;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constructors">
    /** Creates new form FormGrupo */
    public FormGrupo(){
    }
    public FormGrupo(Integer tipo) {
        initComponents();
        initializeMyComponents();
        this.situacao = tipo;
    }
    //</editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormGrupo().setVisible(true);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelPrinc = new javax.swing.JPanel();
        lbDescricao = new javax.swing.JLabel();
        textDescricao = new javax.swing.JTextField();
        panelBotao = new javax.swing.JPanel();
        btnBuscar = new javax.swing.JButton();
        btnNovo = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        jPanelNavegacao = new javax.swing.JPanel();
        btnFirst = new javax.swing.JButton();
        btnPrevious = new javax.swing.JButton();
        btnNext = new javax.swing.JButton();
        btnLast = new javax.swing.JButton();

        setTitle("Grupo");
        setName("formGrupo"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        panelPrinc.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, java.awt.Color.gray));

        lbDescricao.setFont(new java.awt.Font("DejaVu Sans", 0, 12));
        lbDescricao.setText("*Descrição");
        lbDescricao.setToolTipText("");
        lbDescricao.setPreferredSize(new java.awt.Dimension(62, 17));

        textDescricao.setBackground(java.awt.Color.white);
        textDescricao.setEditable(false);
        textDescricao.setFont(new java.awt.Font("DejaVu Sans", 0, 12));
        textDescricao.setToolTipText("");
        textDescricao.setMaximumSize(new java.awt.Dimension(40, 40));
        textDescricao.setPreferredSize(new java.awt.Dimension(100, 26));

        javax.swing.GroupLayout panelPrincLayout = new javax.swing.GroupLayout(panelPrinc);
        panelPrinc.setLayout(panelPrincLayout);
        panelPrincLayout.setHorizontalGroup(
            panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelPrincLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(textDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 384, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );
        panelPrincLayout.setVerticalGroup(
            panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelPrincLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panelBotao.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, java.awt.Color.gray));
        panelBotao.setFont(new java.awt.Font("DejaVu Sans", 0, 12));

        btnBuscar.setFont(new java.awt.Font("SansSerif", 0, 10));
        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/find.png"))); // NOI18N
        btnBuscar.setText("Procurar");
        btnBuscar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnBuscarMouseClicked(evt);
            }
        });

        btnNovo.setFont(new java.awt.Font("SansSerif", 0, 10));
        btnNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/new.png"))); // NOI18N
        btnNovo.setText("Novo     ");
        btnNovo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnNovoMouseClicked(evt);
            }
        });

        btnCancel.setFont(new java.awt.Font("SansSerif", 0, 10));
        btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.png"))); // NOI18N
        btnCancel.setText("Cancelar");
        btnCancel.setMaximumSize(new java.awt.Dimension(92, 34));
        btnCancel.setMinimumSize(new java.awt.Dimension(92, 34));
        btnCancel.setPreferredSize(new java.awt.Dimension(92, 34));
        btnCancel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelMouseClicked(evt);
            }
        });

        btnExcluir.setFont(new java.awt.Font("SansSerif", 0, 10));
        btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/delete.png"))); // NOI18N
        btnExcluir.setText("Excluir   ");
        btnExcluir.setMaximumSize(new java.awt.Dimension(92, 34));
        btnExcluir.setMinimumSize(new java.awt.Dimension(92, 34));
        btnExcluir.setPreferredSize(new java.awt.Dimension(92, 34));
        btnExcluir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnExcluirMouseClicked(evt);
            }
        });

        jPanelNavegacao.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnFirst.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnFirst.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/first.png"))); // NOI18N
        btnFirst.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnFirst.setContentAreaFilled(false);
        btnFirst.setEnabled(false);
        btnFirst.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnFirstMouseClicked(evt);
            }
        });

        btnPrevious.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnPrevious.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/previous.png"))); // NOI18N
        btnPrevious.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnPrevious.setContentAreaFilled(false);
        btnPrevious.setEnabled(false);
        btnPrevious.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnPreviousMouseClicked(evt);
            }
        });

        btnNext.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnNext.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/next.png"))); // NOI18N
        btnNext.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnNext.setContentAreaFilled(false);
        btnNext.setEnabled(false);
        btnNext.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnNextMouseClicked(evt);
            }
        });

        btnLast.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnLast.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/last.png"))); // NOI18N
        btnLast.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnLast.setContentAreaFilled(false);
        btnLast.setEnabled(false);
        btnLast.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnLastMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanelNavegacaoLayout = new javax.swing.GroupLayout(jPanelNavegacao);
        jPanelNavegacao.setLayout(jPanelNavegacaoLayout);
        jPanelNavegacaoLayout.setHorizontalGroup(
            jPanelNavegacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelNavegacaoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnFirst)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnPrevious)
                .addGap(10, 10, 10)
                .addComponent(btnNext)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnLast)
                .addContainerGap())
        );
        jPanelNavegacaoLayout.setVerticalGroup(
            jPanelNavegacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelNavegacaoLayout.createSequentialGroup()
                .addGroup(jPanelNavegacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnFirst)
                    .addComponent(btnPrevious)
                    .addComponent(btnNext)
                    .addComponent(btnLast))
                .addContainerGap())
        );

        javax.swing.GroupLayout panelBotaoLayout = new javax.swing.GroupLayout(panelBotao);
        panelBotao.setLayout(panelBotaoLayout);
        panelBotaoLayout.setHorizontalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelBotaoLayout.createSequentialGroup()
                        .addGap(173, 173, 173)
                        .addComponent(jPanelNavegacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelBotaoLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnBuscar, btnCancel, btnExcluir, btnNovo});

        panelBotaoLayout.setVerticalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscar)
                    .addComponent(btnNovo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelNavegacao, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnBuscar, btnCancel, btnExcluir, btnNovo});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(panelPrinc, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelBotao, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelPrinc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelBotao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-520)/2, (screenSize.height-211)/2, 520, 211);
    }// </editor-fold>//GEN-END:initComponents

    // Fecha o formulario
    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        this.setVisible(false);
        if(this.situacao == K_FORM_CADASTRO){
            this.dispose();
        }
    }//GEN-LAST:event_formWindowClosed

    //<editor-fold defaultstate="collapsed" desc="Eventos CRUD ">
    /**
     * Busca e recupera uma lista de grupos de acordo com os filtros informados
     */
    private void btnBuscarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnBuscarMouseClicked
        try{
            if(btnBuscar.isEnabled()){
                // Verifica o estado do botao
                if(this.btnBuscar.getText().startsWith("Procurar")){
                    clearFields(); // Limpa o formulario

                    StateMachineButton.changeState(getLstButton(1),
                                                   StateMachineButton.PROCURAR);

                    StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
                    // Seta os campos como editaveis
                    textDescricao.setEditable(true);
                    this.grupo = new Grupo();
                }
                else{
                    // cria uma nova lista de grupo
                    this.lstObj = new ArrayList();

                    lstObj = this.grupo.recLstGruposDescricao(
                                    this.textDescricao.getText().toUpperCase());

                    // Verifica se ocorreu algum erro na busca de despesa
                    if(this.grupo.getErrorMessage().equals("")){
                        // Verifica se foi recuperado algum objeto
                        if(!lstObj.isEmpty()){
                            StateMachineNavigator.changeState(getLstButton(2),
                             lstObj.size() == 1 ?
                                 StateMachineNavigator.PADRAO :
                                 StateMachineNavigator.PRIMEIRO);

                            StateMachineButton.changeState(getLstButton(1),
                                    StateMachineButton.RECUPERAR);

                            // Apresenta o primeiro grupo
                            mostraGrupo((Grupo)lstObj.get(0));
                        }
                        else{
                            showMessageWarning(ErrorMessage.MSG_GRUPO_BUSCA);
                        }
                    }
                    else{
                        showMessageError(grupo.getErrorMessage());
                    }
                }
            }
        }
        catch(IOException ex){}
    }//GEN-LAST:event_btnBuscarMouseClicked
    
    /**
     * Responsavel por criar um novo objeto grupo ou salva-lo. Dependendo
     * do estado do atual do botao.
     */
    private void btnNovoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNovoMouseClicked
        try{
            if(btnNovo.isEnabled()){
                // Verifica o estado do botao
                if(this.btnNovo.getText().startsWith("Novo")){
                    clearFields(); // Limpa o formulario
                    StateMachineButton.changeState(getLstButton(1),
                                                       StateMachineButton.NOVO);
                    StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);

                    // Cria uma novo grupo e seta os campos para edicao
                    this.grupo = new Grupo();
                    textDescricao.setEditable(true);
                }
                else{
                    mapFields(); // Mapeia os campos para insercao
                    boolean flag = false;

                    // Verifica se e uma novo grupo ou se e apenas para atulizar
                    if(this.grupo.isNew()){
                        flag = this.grupo.insert();

                        if(flag){
                            this.lstObj = null;
                            StateMachineButton.changeState(getLstButton(1),
                                                     StateMachineButton.SALVAR);
                        }
                    }
                    else{
                        flag = this.grupo.update();

                        if(flag){
                            mudarEstadoNavegacao();
                            StateMachineButton.changeState(getLstButton(1),
                                                   StateMachineButton.CANCELAR);
                        }
                    }

                    // Verifica se foi inserida com sucesso no banco de dados
                    if(flag){
                        this.grupo.setIsNew(false);
                        textDescricao.setEditable(false);
                    }
                    else{
                        showMessageError(grupo.getErrorMessage());
                    }
                }
            }
        }
        catch(IOException ex){ }
    }//GEN-LAST:event_btnNovoMouseClicked

    /**
     * Cancela uma acao corrente de insercao ou edicao. Responsavel tambem por
     * abrir um registro para edicao.
     */
    private void btnCancelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelMouseClicked
        try{
            if(btnCancel.isEnabled()){
                // Verifica o estado do botao
                if(this.btnCancel.getText().startsWith("Cancelar")){

                    // Realiza a confirmacao da acao pelo usuario
                    if(JOptionPane.showConfirmDialog(this, "Confirma o cancelam"
                         +"ento?", "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION){

                        textDescricao.setEditable(false);


                        if(grupo.isNew()){
                            clearFields();
                            StateMachineButton.changeState(getLstButton(1),
                                                    StateMachineButton.INICIAL);
                        }
                        else{
                            StateMachineButton.changeState(getLstButton(1),
                                                   StateMachineButton.CANCELAR);
                            mudarEstadoNavegacao();
                        }
                    }
                }
                else{
                    textDescricao.setEditable(true);
                    this.grupo.setWasUpdated(true);
                    StateMachineButton.changeState(getLstButton(1),
                                                     StateMachineButton.EDITAR);
                    StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
                }
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnCancelMouseClicked

    /**
     * Exclui um grupo da base de dados
     */
    private void btnExcluirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnExcluirMouseClicked
        try{
            if((btnExcluir.isEnabled())){
                // Realiza a confirmacao da acao pelo usuario
                if(JOptionPane.showConfirmDialog(this, "Confirma a exclusão?",
                       "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                       JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION){

                    boolean flag = this.grupo.delete();
                    if(flag){
                        clearFields();

                        textDescricao.setEditable(false);

                        // Verifica o tamanho da lista
                        if(lstObj != null){
                            // Remove o item da lista corrente
                            lstObj.remove(this.posicao);

                            // Posiciona na base de navegacao
                            mudarEstadoNavegacao();

                            if(lstObj.isEmpty()){
                                StateMachineButton.changeState(getLstButton(1),
                                                    StateMachineButton.EXCLUIR);
                            }
                            else{
                                StateMachineButton.changeState(getLstButton(1),
                                                   StateMachineButton.CANCELAR);
                            }
                        }
                        else{
                            StateMachineButton.changeState(getLstButton(1),
                                                    StateMachineButton.EXCLUIR);
                        }
                    }
                    else{
                        showMessageError(grupo.getErrorMessage());
                    }
                }
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnExcluirMouseClicked
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Barra Navegacao">
    /**
     * Move para a primeira posicao da lista de grupos
     */
    private void btnFirstMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnFirstMouseClicked
        try{
            // Verifica o tamanho da lista de grupo
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnFirst.isEnabled()){

                // Posiciona na posicao inicial
                StateMachineNavigator.changeState(getLstButton(2),
                                                StateMachineNavigator.PRIMEIRO);
                this.posicao = 0;
                mostraGrupo((Grupo)lstObj.get(this.posicao));
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnFirstMouseClicked

    /**
     * Posiciona na posicao anterior da lista
     */
    private void btnPreviousMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnPreviousMouseClicked
        try{
            // Verifica o tamanho da lista de grupo
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnPrevious.isEnabled()){

                this.posicao--; // Recebe a proxima posicao

                if(this.posicao >= 1){
                    StateMachineNavigator.changeState(getLstButton(2),
                                          StateMachineNavigator.ANTERIOR_MAIOR);
                }
                else{
                    StateMachineNavigator.changeState(getLstButton(2),
                                          StateMachineNavigator.ANTERIOR_MENOR);
                }

                mostraGrupo((Grupo)lstObj.get(this.posicao));
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnPreviousMouseClicked

    /**
     * Move para o proximo grupo da lista
     */
    private void btnNextMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNextMouseClicked
        try{
            // Verifica o tamanho da lista de grupo
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnNext.isEnabled()){

                this.posicao++; // Recebe a proxima posicao

                if(this.posicao >= (lstObj.size() - 1)){
                    StateMachineNavigator.changeState(getLstButton(2),
                                          StateMachineNavigator.PROXIMO_MENOR);
                }
                else{
                    StateMachineNavigator.changeState(getLstButton(2),
                                          StateMachineNavigator.PROXIMO_MAIOR);
                }

                mostraGrupo((Grupo)lstObj.get(this.posicao));
            }
        }
        catch(Exception ex){ }
    }//GEN-LAST:event_btnNextMouseClicked

    /**
     * Move para a ultima posicao da lista de grupos
     */
    private void btnLastMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnLastMouseClicked
        try{
            // Verifica o tamanho da lista de grupo
            if(!lstObj.isEmpty() && lstObj.size() > 0 && btnLast.isEnabled()){

                // Posiciona na posicao final
                StateMachineNavigator.changeState(getLstButton(2),
                                                StateMachineNavigator.ULTIMO);
                this.posicao = lstObj.size() - 1;
                mostraGrupo((Grupo)lstObj.get(this.posicao));
            }
        }
        catch(Exception ex){ }

    }//GEN-LAST:event_btnLastMouseClicked
    //</editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnFirst;
    private javax.swing.JButton btnLast;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnPrevious;
    private javax.swing.JPanel jPanelNavegacao;
    private javax.swing.JLabel lbDescricao;
    private javax.swing.JPanel panelBotao;
    private javax.swing.JPanel panelPrinc;
    private javax.swing.JTextField textDescricao;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Methods">
    // Messagem de erro
    private void showMessageError(String msg){
        JOptionPane.showMessageDialog(this, msg, "Grupo",
                                                    JOptionPane.ERROR_MESSAGE);
    }

    // Messagem de alerta
    private void showMessageWarning(String msg){
        JOptionPane.showMessageDialog(this, msg, "Grupo",
                                                   JOptionPane.WARNING_MESSAGE);
    }

    // Recupera a lista de botoes do formulario
    private ArrayList<JButton> getLstButton(Integer situacao){
        ArrayList<JButton> lstButton = new ArrayList<JButton>();

        if(situacao == 1){
            lstButton.add(this.btnBuscar);
            lstButton.add(this.btnNovo);
            lstButton.add(this.btnCancel);
            lstButton.add(this.btnExcluir);
        }
        else{
            lstButton.add(this.btnFirst);
            lstButton.add(this.btnPrevious);
            lstButton.add(this.btnNext);
            lstButton.add(this.btnLast);
        }

        return lstButton;
    }

    // Limpa os campos do formulario
    private void clearFields(){
        textDescricao.setText("");
    }

    // Transfere os campos para o objeto para persistencia
    private void mapFields(){
        this.grupo.setNome(this.textDescricao.getText().toUpperCase());
        this.textDescricao.setText(this.textDescricao.getText().toUpperCase());
    }

    // Realiza a apresentacao dos grupos recuperados no formulario
    private void mostraGrupo(Grupo obj){
        this.grupo = obj;
        this.textDescricao.setText(obj.getNome());
        this.textDescricao.setEditable(false);
    }

    // Inicializa o estados de todos os botoes
    private void initializeMyComponents(){
        try{
            StateMachineButton.changeState(getLstButton(1),
                                                  StateMachineButton.INICIAL);
            StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
            clearFields();
        }
        catch(IOException ex){}
    }

    // Volta ao estado da navegacao
    private void mudarEstadoNavegacao() throws IOException{

        if(lstObj != null){
            // Verifica se existe a posicao na lista
            boolean exists = this.posicao < this.lstObj.size() ? true : false;

            // Decrementa uma posicao caso a ultima tenha sido removida
            if(!exists) this.posicao--;

            // Verifica se a lista esta vazia
            if(lstObj.isEmpty()){
                clearFields();
                StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
            }
            // Verifica se o tamanho da lista e 1
            else{
                mostraGrupo((Grupo)lstObj.get(this.posicao));

                if(lstObj.size() <= 1){
                    StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.PADRAO);
                }
                else{
                    // Verifica qual a posicao que se encontra
                    if(this.posicao == 0){
                        StateMachineNavigator.changeState(getLstButton(2),
                                                StateMachineNavigator.PRIMEIRO);
                    }
                    else if(this.posicao == (lstObj.size() - 1)){
                        StateMachineNavigator.changeState(getLstButton(2),
                                                  StateMachineNavigator.ULTIMO);
                    }
                    else{
                        StateMachineNavigator.changeState(getLstButton(2),
                                          StateMachineNavigator.ANTERIOR_MAIOR);
                    }
                }
            }
        }
    }
    //</editor-fold>
}
